package org.alex.samples.web;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.alex.samples.model.CommomMessageResultVO;
import org.alex.samples.model.ExamUserVO;
import org.alex.samples.model.ExcelUtils;
import org.alex.samples.model.User;
import org.alex.samples.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class UserController {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private LocaleResolver localeResolver;
	
	@Autowired
	private MessageSource messageSource;
	
	@RequestMapping(value = "/changeLocale")
	public String changeLocale(HttpServletRequest request,HttpServletResponse response,String localeType){
		if("en_US".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.US);
		}else if("zh_CN". equals(localeType)){
			localeResolver.setLocale(request, response, Locale.CHINA);
		}
		return "redirect:/users";
	}
	
	@RequestMapping("/users")
	public String users(Model model){
		List<ExamUserVO> list = userService.findAllUsers();
		
		model.addAttribute("edit", messageSource.getMessage("page.index.edit", null,LocaleContextHolder.getLocale()));
		model.addAttribute("userList", list);
		return "user/userList";
	}
	
	@RequestMapping(value = "/add",method = RequestMethod.GET)
	public String toadd(Model model){
		model.addAttribute("user", new User());
		return "user/add";
	}
	
	@RequestMapping(value = "/add",method = RequestMethod.POST)
	public String add(RedirectAttributes redirectAttributes,@Validated User user,BindingResult result){
		if(result.hasErrors()){
			return "user/add";
		}
		try {
			userService.createUser(user);
			redirectAttributes.addFlashAttribute("message", "添加成功.");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/users";
	}
	
	@RequestMapping(value = "/edit/{id}",method = RequestMethod.GET)
	public String toEdit(Model model,@PathVariable String id){
		User user = userService.getUserById(id);
		model.addAttribute("user", user);
		return "user/edit";
	}
	
	@RequestMapping(value = "/edit/{id}",method = RequestMethod.POST)
	public String edit(RedirectAttributes redirectAttributes, User user,@PathVariable String id){
		try {
			//user.setId("id");
			userService.editUser(user);
			redirectAttributes.addFlashAttribute("message", "修改成功.");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/users";
	}
	
	@RequestMapping(value = "/delete/{id}",method = RequestMethod.GET)
	public String delete(RedirectAttributes redirectAttributes, @PathVariable String id){
		try {
			userService.delete(id);
			redirectAttributes.addFlashAttribute("message", "删除成功.");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", "删除失败.");
			e.printStackTrace();
		}
		return "redirect:/users";
	}
	
	@ResponseBody
	@RequestMapping(value="/uploadFile")
	public CommomMessageResultVO uploadFile(@RequestParam(value = "uploadFile" ) MultipartFile[] uploadFile,HttpSession session,Model model){
		CommomMessageResultVO resultVO = new CommomMessageResultVO();
		MultipartFile uploadSimpleFile = uploadFile[0];
		String fileName = uploadSimpleFile.getOriginalFilename();
		//获取文件后缀名
		String postfix = fileName.substring(fileName.lastIndexOf("."));
		Map<String,String> messageMap = new HashMap<String,String>();

		
		try{
		if(ExcelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix) || ExcelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
			userService.saveStudentByExcel(uploadSimpleFile.getInputStream(),postfix);
			resultVO.setSuccess(true);
		}else{
			messageMap.put("message", "文件格式不正确。");
			resultVO.setMessage(messageMap);
		      }
		}catch(Exception e){
			e.printStackTrace();
			messageMap.put("message", "批量导入失败");
			resultVO.setMessage(messageMap);
		}
		return resultVO;
		
	}
	
	

}
